package com.demo.web;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.demo.entity.CustomBase;
import com.demo.entity.CustomCrud;
import com.demo.server.CustomServer;
import com.jweb.annotaion.JAutowired;
import com.jweb.annotaion.JController;
import com.jweb.annotaion.JParam;
import com.jweb.config.def.CharSet;
import com.jweb.core.handle.Controller;
import com.jweb.log.Logger;
import com.jweb.util.FormatUtil;
import com.jweb.util.SecurityUtil;

/**
 * 
 * 
 * @author Yuan
 *
 */
@JController("/custom")
public class CustomController extends Controller {
	private Logger log = Logger.getLogger(this.getClass());

	@JAutowired
	private CustomServer customServer;

	/**
	 * 新增/修改 详情页面
	 */
	public void info(@JParam("{1}") int id) {
		setInfoByID(id);
	}

	public void show(@JParam("{1}") int id) {
		setInfoByID(id);
	}

	public void add(@JParam("params") String params) {
		log.info("来了一个自定义报表新增操作。");
		try {
			if (!FormatUtil.isEmpty(params))
				params = SecurityUtil.Base64Decode(params);
			log.info(params);
			String[] ps = params.split(";");
			CustomBase defForm = new CustomBase();
			List<CustomCrud> searchForm = new ArrayList<CustomCrud>();
			List<CustomCrud> colForm = new ArrayList<CustomCrud>();
			List<CustomCrud> editForm = new ArrayList<CustomCrud>();
			List<CustomCrud> addForm = new ArrayList<CustomCrud>();
			List<CustomCrud> delForm = new ArrayList<CustomCrud>();
			for (String str : ps) {
				int spli = str.indexOf(",");
				if (spli <= 0)
					continue;
				String startOf = str.substring(0, spli);
				Map<String, String> map = getUrlToMap(str, spli);
				if (map.size() == 0)
					continue;
				if (startOf.equalsIgnoreCase("defForm")) {
					defForm.setId(FormatUtil.toInt(map.get("id")));
					defForm.setName(URLDecoder.decode(map.get("name"), CharSet.UTF8));
					defForm.setBoCheckbox(FormatUtil.toInt(map.get("boCheckbox")));
					defForm.setBoExport(FormatUtil.toInt(map.get("boExport")));
					defForm.setBoLimit(FormatUtil.toInt(map.get("boLimit")));
					defForm.setLimiSize(FormatUtil.toInt(map.get("limiSize")));
					defForm.setOperat("操作员");
					defForm.setSqlSelect(URLDecoder.decode(FormatUtil.toString(map.get("sqlSelect")), CharSet.UTF8));
				} else {
					String[] _names = FormatUtil.toString(map.get("name")).split("&");
					String[] _codes = FormatUtil.toString(map.get("code")).split("&");
					String[] _types = FormatUtil.toString(map.get("type")).split("&");
					String[] _boNulls = FormatUtil.toString(map.get("boNull")).split("&");
					String[] _boShows = FormatUtil.toString(map.get("boShow")).split("&");
					String[] _defs = FormatUtil.toString(map.get("def")).split("&");
					for (int i = 0; i < _codes.length; i++) {// 字段名是每个都有的
						CustomCrud cc = new CustomCrud();
						String name = FormatUtil.toString(getArrayVal(_names, i, ""));
						cc.setName(URLDecoder.decode(name, CharSet.UTF8));
						cc.setCode(URLDecoder.decode(getArrayVal(_codes, i, "").toString(), CharSet.UTF8));
						cc.setType(FormatUtil.toInt(getArrayVal(_types, i, "")));
						cc.setBoShow(FormatUtil.toInt(getArrayVal(_boShows, i, "")));
						cc.setBoNull(FormatUtil.toInt(getArrayVal(_boNulls, i, "")));
						cc.setDef(URLDecoder.decode(getArrayVal(_defs, i, "").toString(), CharSet.UTF8));
						if (startOf.equalsIgnoreCase("SearchForm")) {
							cc.setOperatType(CustomCrud.EopType.select.getType());
							searchForm.add(cc);
						} else if (startOf.equalsIgnoreCase("ColForm")) {
							cc.setOperatType(CustomCrud.EopType.showCol.getType());
							colForm.add(cc);
						} else if (startOf.equalsIgnoreCase("AddForm")) {
							defForm.setSqlInsert(URLDecoder.decode(FormatUtil.toString(map.get("sqlInsert")), CharSet.UTF8));
							cc.setOperatType(CustomCrud.EopType.insert.getType());
							addForm.add(cc);
						} else if (startOf.equalsIgnoreCase("EditForm")) {
							defForm.setSqlUpdate(URLDecoder.decode(FormatUtil.toString(map.get("sqlUpdate")), CharSet.UTF8));
							cc.setOperatType(CustomCrud.EopType.update.getType());
							editForm.add(cc);
						} else if (startOf.equalsIgnoreCase("DelForm")) {
							defForm.setSqlDelete(URLDecoder.decode(FormatUtil.toString(map.get("sqlDelete")), CharSet.UTF8));
							cc.setOperatType(CustomCrud.EopType.delete.getType());
							delForm.add(cc);
						}
					}
				}
			}
			log.info("获取参数CustomBase:{}", JSON.toJSONString(defForm));
			log.info("获取参数searchForm:{}", JSON.toJSONString(searchForm));
			log.info("获取参数colForm:{}", JSON.toJSONString(colForm));
			log.info("获取参数editForm:{}", JSON.toJSONString(editForm));
			log.info("获取参数addForm:{}", JSON.toJSONString(addForm));
			log.info("获取参数delForm:{}", JSON.toJSONString(delForm));
			List<CustomCrud> listAll = new ArrayList<CustomCrud>();
			listAll.addAll(searchForm);
			listAll.addAll(colForm);
			listAll.addAll(editForm);
			listAll.addAll(addForm);
			listAll.addAll(delForm);
			if (listAll.size() == 0)
				toWriterText("Error:List size is 0 !!");
			else {
				// 入库
				if (defForm.getId() > 0) {
					customServer.delCustomCrudByPId(defForm.getId());
					customServer.editCustomBean(defForm);
					customServer.customCrudAddList(defForm.getId(), listAll);
				} else {
					customServer.customAdd(defForm, listAll);
				}
				toWriterText("OK");
			}
		} catch (Exception e) {
			e.printStackTrace();
			toWriterText("Error:" + e.getMessage());
		}

	}

	private Map<String, String> getUrlToMap(String str, int spli) {
		String[] param = str.substring(spli + 1).split("&");
		Map<String, String> map = new HashMap<String, String>();
		for (String str2 : param) {
			String[] keyVal = str2.split("=");
			String sp = "&";
			if (FormatUtil.isEmpty(map.get(keyVal[0])))
				sp = "";
			if (keyVal.length == 1)
				continue;
			map.put(keyVal[0], FormatUtil.toString(map.get(keyVal[0])) + sp + FormatUtil.toString(keyVal[1]));
		}
		return map;
	}

	/**
	 * 获取数组obj 指定下标index 的值，如果无法获取,反回默认值def。
	 */
	private <T> T getArrayVal(T[] obj, int index, T def) {
		if (obj.length > index) {
			return obj[index];
		} else {
			return def;
		}
	}

	private void setInfoByID(int id) {
		CustomBase cusBase = new CustomBase();
		List<CustomCrud> crudselect = new ArrayList<CustomCrud>();
		List<CustomCrud> crudshow = new ArrayList<CustomCrud>();
		List<CustomCrud> crudinsert = new ArrayList<CustomCrud>();
		List<CustomCrud> crudupdate = new ArrayList<CustomCrud>();
		List<CustomCrud> cruddelete = new ArrayList<CustomCrud>();
		if (id > 0) {
			cusBase = customServer.getCustomBase(id);
			if (cusBase != null) {
				// select(1), showCol(2), insert(3), update(4), delete(5);
				crudselect = customServer.getCustomCrudList(id, CustomCrud.EopType.select.getType(), id + "select");
				crudshow = customServer.getCustomCrudList(id, CustomCrud.EopType.showCol.getType(), id + "showCol");
				crudinsert = customServer.getCustomCrudList(id, CustomCrud.EopType.insert.getType(), id + "insert");
				crudupdate = customServer.getCustomCrudList(id, CustomCrud.EopType.update.getType(), id + "update");
				cruddelete = customServer.getCustomCrudList(id, CustomCrud.EopType.delete.getType(), id + "delete");
			}
		}
		setAttr("CusBase", cusBase);
		setAttr("crudselect", crudselect);
		setAttr("crudshow", crudshow);
		setAttr("crudinsert", crudinsert);
		setAttr("crudupdate", crudupdate);
		setAttr("cruddelete", cruddelete);
	}

	public static void main(String[] args) throws UnsupportedEncodingException {
		System.out.println(URLDecoder.decode("", CharSet.UTF8));
	}
}
